package com.tmt.im.jpa.entity;

import com.tmt.data.jpa.converter.StringAndListConverter;
import com.tmt.data.jpa.entity.TmtBaseUser;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serial;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * 金子塔用户
 *
 * @Description TODO
 * @Author wuyi
 * @Date 2024/7/13 17:19
 * @Version 1.0
 **/
@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Tag(name = "im_user", description = "用户表")
@Entity
@Table(name = "im_user")
public class IMUser extends TmtBaseUser implements UserDetails {

    @Serial
    private static final long serialVersionUID = -2167910997846539112L;

    /**
     * 用户头像，存储的是头像图片的访问URI。
     */
    @Schema(name = "avatar", description = "用户头像")
    private String avatar;

    @Schema(name = "memberCode", description = "会员号")
    @Column(length = 20, unique = true)
    private String memberCode;

    @Schema(name = "nickname", description = "用户昵称")
    @Column(length = 100)
    private String nickname;

    @Schema(name = "mobile", description = "手机号码")
    @Column(length = 16, unique = true)
    private String mobile;

    @Schema(name = "deviceType", description = "设备类型")
    @Column(length = 10)
    private String deviceType;

    @Schema(name = "deviceIds", description = "曾经设备Id过的设备ID列表")
    @Convert(converter = StringAndListConverter.class)
    @Column(columnDefinition = "VARCHAR(1024)")
    private List<String> deviceIds;

    @Schema(name = "certName", description = "身份证姓名")
    @Column(length = 100)
    private String certName;

    @Schema(name = "certNo", description = "身份证号")
    @Column(length = 18)
    private String certNo;

    @Schema(name = "grade", description = "会员等级")
    private Integer grade;

    @Schema(name = "introduce", description = "个性签名")
    private String introduce;

    @Schema(name = "imToken", description = "云信令牌")
    private String imToken;

    @Schema(name = "settingId", description = "个人配置对象的ID, 方便利用Ignite直接从用户对象获取配置对象")
    private Long settingId;

    @Schema(name = "walletId", description = "个人钱包的ID, 方便利用Ignite直接从用户对象获取钱包对象")
    private Long walletId;

    @Schema(description = "授权服务器上用户信息最新更新时间")
    @Temporal(TemporalType.TIMESTAMP)
    private Timestamp updateTime;

    @Schema(name = "parent", description = "所属的主账号")
    @ManyToOne(cascade = {CascadeType.REFRESH}, fetch = FetchType.LAZY)
    private IMUser parent;

    /**
     * 当前用户的个性化设置。
     */
    @OneToOne(mappedBy = "owner", cascade = {CascadeType.PERSIST, CascadeType.REFRESH}, fetch = FetchType.LAZY, optional = false)
    private PersonalSetting setting;

    @OneToOne(mappedBy = "owner", cascade = {CascadeType.PERSIST, CascadeType.REFRESH}, fetch = FetchType.LAZY, optional = false)
    private Wallet wallet;

    @OneToMany(mappedBy = "user", cascade = {CascadeType.REFRESH}, fetch = FetchType.LAZY)
    private List<IMUserRole> userRoles;

    @OneToMany(mappedBy = "creator", cascade = {CascadeType.REFRESH}, fetch = FetchType.LAZY)
    private List<RedPackageDetail> redPackageDetails;

    @OneToMany(mappedBy = "creator", cascade = {CascadeType.REFRESH}, fetch = FetchType.LAZY)
    private List<RedPackage> redPackages;
    /**
     * 用户创建的黑名单
     */
    @OneToMany(mappedBy = "creator", cascade = {CascadeType.REFRESH}, fetch = FetchType.LAZY)
    private List<BlackBill> blackBills;

    /**
     * 用户绑定的银行卡列表
     */
    @OneToMany(mappedBy = "owner", cascade = {CascadeType.REFRESH}, fetch = FetchType.LAZY)
    private List<BankCard> bankCards;

    /**
     * 所属的副账号
     */
    @OneToMany(mappedBy = "parent", cascade = {CascadeType.REFRESH}, fetch = FetchType.LAZY)
    private List<IMUser> children;

    /**
     * 审核通过后创建的好友对象。
     */
    @OneToMany(mappedBy = "creator", cascade = {CascadeType.REFRESH}, fetch = FetchType.LAZY)
    private List<IMFriendGroup> friendGroups;

    /**
     * 发布的公告列表
     */
    @OneToMany(mappedBy = "creator", cascade = {CascadeType.REFRESH}, fetch = FetchType.LAZY)
    private List<SystemNotify> systemNotifies;

    /**
     * 提现绑定参数
     */
    @OneToMany(mappedBy = "creator", cascade = {CascadeType.REFRESH}, fetch = FetchType.LAZY)
    private List<WithdrawBindingParam> bindingParams;

    @Transactional(readOnly = true)
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<IMAuthority> list = new ArrayList<>();
        for (IMUserRole userRole : this.getUserRoles()) {
            for (IMRoleAuthority roleAuthority : userRole.getRole().getRoleAuthorities()) {
                if (!list.contains(roleAuthority.getAuthority())) {
                    list.add(roleAuthority.getAuthority());
                }
            }
        }
        return list;
    }

}
